package com.w.utils.code;
/**
 *
 **/

import com.w.utils.id.IdUtils;
import com.w.utils.sign.Base64;
import com.w.utils.spring.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author weiwei
 * @Date 2021-03-02 11:03
 * @description 验证码控制层
 **/
@RestController
public class CaptchaController {

    @Autowired
    private RedisCache redisCache;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public Map<String,Object> getCode(HttpServletResponse response) throws IOException
    {
        // 生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        // 唯一标识
        String uuid = IdUtils.simpleUUID();
        String verifyKey = "captcha_codes:" + uuid;

        redisCache.setCacheObject(verifyKey, verifyCode, 2, TimeUnit.MINUTES);
        // 生成图片
        int w = 111, h = 36;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(w, h, stream, verifyCode);
        try
        {
            Map<String,Object> result = new HashMap<>();
            result.put("uuid", uuid);
            result.put("img", Base64.encode(stream.toByteArray()));
            return result;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            Map<String,Object> result = new HashMap<>();
            result.put("code",500);
            return result;
        }
        finally
        {
            stream.close();
        }
    }
}
